package com.zhongxi.guoyuan.view.user;

import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.DividendDetailAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.user.DividendRecorderResult;
import com.zhongxi.guoyuan.entity.user.TodayEarningResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.MainActivity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import static com.zhongxi.guoyuan.R.id.tvBonusPoint;

//import android.support.annotation.RequiresApi;

public class MyDividendActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

//    private ImageView ivShare;
//    private ImageView ivGetCash;
    private ImageView ivRecord;
    private LinearLayout linearInfo;
    private PullToRefreshListView lvList;
    private ImageView ivImg;
    private TextView tvName;
    private TextView tvPhone;
    private TextView tvPoint;
    private TextView tvIdentify;
    private TextView tvMoney;
    private TextView tvTotalMoney;

    private int type = 0;
    private List<DividendRecorderResult.RecodeCoinRecordDetailResult> data = new ArrayList<>();
    private DividendDetailAdapter adapter;
    private String flag;
    private TextView tvTime;
    private ImageView ivMeirong;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_my_dividend);
        initTitle();
        tvTitle.setText("分润看一看");
        ivRecord = (ImageView) findViewById(R.id.ivRecord);
        ivMeirong = (ImageView) findViewById(R.id.ivMeirong);
        linearInfo = (LinearLayout) findViewById(R.id.linearInfo);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        lvList.setVisibility(View.GONE);

        //用户信息
        ivImg = (ImageView) findViewById(R.id.ivImg);
        tvName = (TextView) findViewById(R.id.tvName);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvPoint = (TextView) findViewById(R.id.tvPoint);
        tvIdentify = (TextView) findViewById(R.id.tvIdentify);
        tvMoney = (TextView) findViewById(R.id.tvMoney);
        tvTotalMoney = (TextView) findViewById(R.id.tvTotalMoney);
    }

    @Override
    protected void initData() {
        super.initData();
        initTime();
        adapter = new DividendDetailAdapter(context, data);
        lvList.setAdapter(adapter);
        flag = "today";
        getServer(Url.MY_TODAY_EARNINGS, null, "", false, null, "get");
    }

    private void initTime() {
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH)+1;
        int day = c.get(Calendar.DAY_OF_MONTH);
        tvTime.setText("今天是"+year+"年"+month+"月"+day+"日");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("today".equals(flag)){
                TodayEarningResult result = gson.fromJson(response, TodayEarningResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                initInfo(result);
            }else if("recorder".equals(flag)){
                DividendRecorderResult result = gson.fromJson(response, DividendRecorderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(pageNum==1){
                    data.clear();
                }
                lvList.onRefreshComplete();
                if(result.getRecode().size()>0){
                    data.addAll(result.getRecode());
                }
                adapter.notifyDataSetChanged();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 初始化数据
     * @param result
     */
    private void initInfo(TodayEarningResult result) {
        if(null!=result.getUserInfo()&&!"".equals(result.getUserInfo())){
            TodayEarningResult.UserInfoCoinRecordDetailResult userInfo = result.getUserInfo();
            if(null!=userInfo.getAvatar()&&!"".equals(userInfo.getAvatar())){
                Glide.with(context).load(Url.BASE_URL+userInfo.getAvatar()).placeholder(R.mipmap.iv_eg).transform(new GlideRoundTransform(context, 20)).into(ivImg);
            }
            if(null!=userInfo.getShopname()&&!"".equals(userInfo.getShopname())){
                tvName.setText("店名："+userInfo.getShopname());
            }else{
                tvName.setText(R.string.app_name);
            }
            if(null!=userInfo.getMphone()&&!"".equals(userInfo.getMphone())){
                tvPhone.setText("手机号："+MyApplication.getInstance().parseSecutiryKey(userInfo.getMphone()));
            }else{
                tvPhone.setText("");
            }
            String sb = "";
            if(null!=userInfo.getIsprivilege()){
                if("1".equals(userInfo.getIsprivilege())){
                    sb+="权益会员";
                    try {
                        if (null != result.getRights() && !"".equals(result.getRights())) {
                            if ("1".equals(result.getRights().get(0).getUsertype())) {
                                sb += "(" + result.getRights().get(0).getEtime() + ")";
                            } else {
                                sb += "(" + result.getRights().get(1).getEtime() + ")";
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            if(null!=sb&&!"".equals(sb)){
                tvIdentify.setText("身份证："+sb.toString());
            }else{
                tvIdentify.setText("身份证：普通会员");
            }
        }
        if(null!=result.getRecode()&&!"".equals(result.getRecode())){
            if(null!=result.getRecode().getSharesgains()&&!"".equals(result.getRecode().getSharesgains())){
                tvMoney.setText(result.getRecode().getSharesgains()+"元");
            }else{
                tvMoney.setText("*元");
            }
        }
        int point = 0;
        if (null != result.getRights() && result.getRights().size() > 0) {
            for (int i = 0; i < result.getRights().size(); i++) {
                if (null != String.valueOf(result.getRights().get(i).getUsertype())) {
                    if (result.getRights().get(i).getUsertype() == 0) {  //股东
                        if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                            point += result.getRights().get(i).getSharesnum();
                    } else {                                                            //权益会员
                        if (null != String.valueOf(result.getRights().get(i).getSharesnum()))
                            point += result.getRights().get(i).getSharesnum();
                    }
                }
            }
        }
        if (null != String.valueOf(point)) {
            tvPoint.setText(String.valueOf(point));
        }else {
            tvPoint.setText("0");
        }
        if(null!=result.getSharesgains()&&!"".equals(result.getSharesgains())){
            tvTotalMoney.setText("目前累积分润:"+result.getSharesgains()+"元");
        }else{
            tvTotalMoney.setText("目前累积分润：*元");
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        ivRecord.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
        ivMeirong.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.ivMeirong:
                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index", 0);
                startActivity(intent);
                break;
            case R.id.ivRecord:
                if(type == 0){
                    type = 1;
                    ivRecord.setImageResource(R.mipmap.iv_record_back);
                    linearInfo.setVisibility(View.GONE);
                    lvList.setVisibility(View.VISIBLE);
                    getRecorder();
                }else if(type == 1){
                    type = 0;
                    ivRecord.setImageResource(R.mipmap.iv_recording);
                    linearInfo.setVisibility(View.VISIBLE);
                    lvList.setVisibility(View.GONE);
                }
                break;
        }
    }

    /**
     * 获取历史收益记录
     */
    private void getRecorder() {
        flag = "recorder";
        String str = "&page="+pageNum;
        getServer(Url.MY_HISTORY_SHARES_GAINS, null, str, false, null, "get");
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getRecorder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum ++;
        getRecorder();
    }
}
